package com.dragon.concurrent.demo.readandwrite;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class ShareData {

    private final char[] buffer;

    private final ReadWriteLock LOCK = new ReadWriteLock(false);

    public ShareData(int size) {
        buffer = new char[size];
        for (int i = 0; i < size; i++) {
            buffer[i] = '$';
        }
    }

    public char[] read() throws InterruptedException {
        try{
            LOCK.readLock();
            return doRead();
        }finally {
            LOCK.readUnLock();
        }
    }

    private char[] doRead() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2L);

        return Arrays.copyOf(buffer, buffer.length);
    }

    public void write(char c) throws InterruptedException {
        try {
            LOCK.writeLock();
            doWrite(c);
        } finally {
            LOCK.writeUnlock();
        }
    }

    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
        }

    }
}
